package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import dao.TeacherService;
import entity.Teacher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@WebServlet("/tc")
public class TeacherReadCtl extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONObject message_jsonObj = new JSONObject();
        response.setContentType("application/json;charset=utf-8");
        String req_jsonStr = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        if(req_jsonObj == null){
            message_jsonObj.put("message","未收到请求信息!");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try {
            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
            Collection<Teacher> teachers = TeacherService.getInstance().findAll(conditionList,pagination);
            message_jsonObj.put("totalNum",pagination.getTotalNum());
            message_jsonObj.put("records",teachers);
            response.getWriter().println(message_jsonObj);
        }catch (SQLException e){
            message_jsonObj.put("message","数据库操作异常!");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        } catch (Exception e) {
            message_jsonObj.put("message","网络异常!");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }
    }
}
